'''
Created on Sep 7, 2010

@author: oabalbin
'''
import os
import glob
import subprocess
from optparse import OptionParser
from collections import deque, defaultdict


def read_files_folder(folderpath,ext):
    # Read files in folder
    myfiles=[]
    for infile in glob.glob( os.path.join(folderpath, '*.'+ext) ):
        myfiles.append(infile)
        #print "current file is: " + infile
    return myfiles

def convert_sam2arf(myfiles):
    '''
    It converts a file in the sam format to a file in the miRDeep format.
    '''
    for thisfile in myfiles:
        print thisfile
        sam_converter_params = ["time","bwa_sam_converter.pl",thisfile, thisfile+'_reads.fa', thisfile+'_reads.arf'] 
        #subprocess.Popen(sam_converter_params)
        subprocess.call(sam_converter_params)
        sam_converter_params=[]
        

def run_miRDeep(myreads, mygenome, mirdeepreads,thisspecie_mature_mirnas, otherspecies_mature_mirnas,thisspecie_hairpin_mirnas, specie):
    '''
    Run mirdeep2 over myfiles
    '''
    
    mirdeep_params = ["time","miRDeep2.pl", myreads, mygenome, mirdeepreads,thisspecie_mature_mirnas, otherspecies_mature_mirnas, \
                      thisspecie_hairpin_mirnas, "-t", specie]
    subprocess.call(mirdeep_params)

'''
/miRDeep2.pl /exds/users/oabalbin/projects/iDEA/trimmed_sequences/tags_and_counts_lane3.mdp 
/exds/tuxedo/version_003_2010_Mar_26/bowtie_indexes/hg18_illumina.fa 
/exds/users/oabalbin/projects/iDEA/mirdeep/tags_and_counts_lane3.arf 
mature_hsa_T.fa mature_other_sp.fa hairpin_hsa.fa -t Human 2> mirdeep_iDEA_small_lane3.log
''' 



if __name__ == '__main__':
    
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-d", "--folder", dest="folder",
                            help="Path to the folder that contains the .sam files")
    (options, args) = optionparser.parse_args()
    
    folderpath = options.folder
    #folderpath = '/data/projects/mirnas/mirnas_discovery/sam_files_MIR/test/'
    myfiles = read_files_folder(folderpath,'sam')
    convert_sam2arf(myfiles)